<template>
    <div class="app-container">
        <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="80px" size="small">
            <el-form-item label="机构名称" prop="orgName">
                <el-input v-model="queryParams.orgName" clearable placeholder="请输入机构名称" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <div style="float: right">
                <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </div>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button v-hasPermi="['system:SysOrg:add']" icon="el-icon-plus" plain size="mini" type="primary"
                    @click="handleAdd">新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button v-hasPermi="['system:SysOrg:export']" icon="el-icon-download" plain size="mini" type="warning"
                    @click="handleExport">导出
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-adaptive v-loading="loading" :data="SysOrgList" stripe highlight-current-row
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" :border="true" height="200px"
            row-key="orgId">
            <el-table-column :align="'center'" label="机构名称" prop="orgName" />
            <el-table-column :align="'center'" label="机构code" prop="orgCode" />
            <el-table-column :align="'center'" label="联系人" prop="linkMan" />
            <el-table-column :align="'center'" label="联系人电话" prop="phone" />
            <el-table-column :align="'center'" label="排序" prop="orderNum" />
            <el-table-column :align="'center'" label="备注" prop="remark" />
            <el-table-column :align="'center'" label="状态" width="100">
                <template #default="scope">
                    <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
                        @change="handleStatusChange(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column :align="'center'" class-name="small-padding fixed-width" label="操作">
                <template #default="scope">
                    <el-button v-hasPermi="['system:SysOrg:edit']" icon="el-icon-edit" size="mini" type="success"
                        @click="handleUpdate(scope.row)">修改
                    </el-button>
                    <el-button v-hasPermi="['system:menu:add']" icon="el-icon-plus" size="mini" type="primary"
                        @click="handleAdd(scope.row)">新增
                    </el-button>
                    <el-button v-hasPermi="['system:SysOrg:remove']" icon="el-icon-delete" size="mini" type="danger"
                        @click="handleDelete(scope.row)">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total"
            @pagination="getList" />

        <!-- 添加或修改机构对话框 -->
        <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" append-to-body width="50%">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
                <el-row :gutter="40">
                    <el-col :span="24">
                        <el-form-item label="上级机构" prop="parentId">
                            <treeSelect v-model="form.parentId" :normalizer="normalizer" :options="orgOptions"
                                :show-count="true" placeholder="选择上级机构" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="机构名称" prop="orgName">
                            <el-input v-model="form.orgName" placeholder="请输入机构名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="机构编码" prop="orgCode">
                            <el-input v-model="form.orgCode" :disabled="isEdit" maxlength="16" placeholder="请输入机构code"
                                show-word-limit />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="机构类型" prop="orgClass">
                            <el-select v-model="form.orgClass" filterable placeholder="请选择机构类型">
                                <!-- <el-option v-for="dict in dict.type.org_class" :key="dict.value" :label="dict.label"
                                    :value="dict.value"></el-option> -->
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="机构等级">
                            <el-select v-model="form.orgLevel" placeholder="请选择机构类型">
                                <!-- <el-option v-for="dict in dict.type.org_level" :key="dict.value" :label="dict.label"
                                    :value="dict.value"></el-option> -->
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="联系人" prop="linkMan">
                            <el-input v-model="form.linkMan" placeholder="请输入联系人" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="联系人电话" prop="phone">
                            <el-input v-model="form.phone" maxlength="11" placeholder="请输入联系人电话" show-word-limit />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="联系人邮箱" prop="email">
                            <el-input v-model="form.email" placeholder="请输入联系人邮箱" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="联系人地址" prop="address">
                            <el-input v-model="form.address" placeholder="请输入联系人地址" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="地区名称" prop="region">
                            <el-input v-model="form.region" placeholder="请输入地区名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="地区编码" prop="regionCode">
                            <el-input v-model="form.regionCode" placeholder="请输入地区编码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="社会信用代码" prop="socialCode">
                            <el-input v-model="form.socialCode" placeholder="请输入社会信用代码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="省" prop="province">
                            <el-input v-model="form.province" placeholder="请输入行政区划代码-省" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="市/区" prop="city">
                            <el-input v-model="form.city" placeholder="请输入行政区划代码-市/区" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="县/区" prop="county">
                            <el-input v-model="form.county" placeholder="请输入行政区划代码-县/区" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" class="select-margin">
                        <el-form-item label="助产标识">
                            <el-radio-group v-model="form.deliverMark">
                                <!-- <el-radio v-for="dict in dict.type.deliver_mark" :key="dict.value" :label="dict.value">{{
                                    dict.label }}
                                </el-radio> -->
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" class="select-margin">
                        <el-form-item label="监管标识">
                            <el-radio-group v-model="form.superviseMark">
                                <!-- <el-radio v-for="dict in dict.type.supervise_mark" :key="dict.value" :label="dict.value">{{
                                    dict.label }}
                                </el-radio> -->
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" class="select-margin">
                        <el-form-item label="救治中心标识">
                            <el-radio-group v-model="form.cureMark">
                                <!--    <el-radio v-for="dict in dict.type.cure_mark" :key="dict.value" :label="dict.value">{{
                                    dict.label }}
                                </el-radio> -->
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" class="select-margin">
                        <el-form-item label="档案关联标识">
                            <el-radio-group v-model="form.archivesMark">
                                <!-- <el-radio v-for="dict in dict.type.archives_mark" :key="dict.value" :label="dict.value">{{
                                    dict.label }}
                                </el-radio> -->
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" class="select-margin">
                        <el-form-item label="排序" prop="orderNum">
                            <el-input v-model="form.orderNum" placeholder="请输入排序" type="number" />
                        </el-form-item>
                    </el-col>

                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="机构logo">
                            <image-upload v-model="form.orgImg" :limit="1" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="机构介绍" prop="remark">
                            <el-input v-model="form.remark" :rows="8" placeholder="请输入内容" type="textarea" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { addSysOrg, changeOrgStatus, delSysOrg, getSysOrg, listSysOrg, updateSysOrg } from "@/api/system/sysOrg";
import TreeSelect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
const { proxy } = getCurrentInstance() as any
// dicts: ['archives_mark', 'org_class', 'deliver_mark', 'org_level', 'supervise_mark', 'cure_mark'],
// form 定义的ref
const formRef = ref()
// 按钮loading
let buttonLoading = ref<Boolean>(false)
// 遮罩层
let loading = ref<Boolean>(true)
// 选中数组
let ids = reactive<any[]>([])
// 非单个禁用
let single = ref<Boolean>(true)
// 非多个禁用
let multiple = ref<Boolean>(true)
// 显示搜索条件
let showSearch = ref<Boolean>(true)
// 总条数
let total = ref<number>(0)
// 机构表格数据
let SysOrgList = reactive<any[]>([])
// 下拉框机构树
let orgOptions = reactive<any[]>([])
// 弹出层标题
let title = ref<String>("")
// 是否编辑
let isEdit = ref<Boolean>(false)
// 是否显示弹出层
let open = ref<Boolean>(false)

// 查询参数
let queryParams = reactive<any>({
    pageNum: 1,
    pageSize: 10,
    orgName: undefined,
    orgCode: undefined,
    email: undefined,
    address: undefined,
    phone: undefined,
    linkMan: undefined,
    applyStatus: "",
    parentId: undefined,
    parentIds: undefined,
    region: undefined,
    regionCode: undefined,
    orgImg: undefined,
    socialCode: undefined,
    province: undefined,
    city: undefined,
    county: undefined,
    deliverMark: undefined,
    superviseMark: undefined,
    cureMark: undefined,
    archivesMark: undefined,
    orgClass: undefined,
    orgLevel: undefined,
    orderNum: undefined,
    status: undefined
})
// 表单参数
let form = reactive({
    orgName: undefined,
    orgCode: undefined,
    email: undefined,
    address: undefined,
    phone: undefined,
    linkMan: undefined,
    applyStatus: "",
    parentId: "",
    parentIds: undefined,
    region: undefined,
    regionCode: undefined,
    orgImg: undefined,
    socialCode: undefined,
    province: undefined,
    city: undefined,
    county: undefined,
    deliverMark: "",
    superviseMark: "",
    cureMark: "",
    archivesMark: "",
    orgClass: "",
    orgLevel: "",
    orderNum: undefined,
    status: "",
    orgId: "",
    remark: ""
})

// 表单校验
let rules = reactive({
    orgId: [
        { required: true, message: "机构主键不能为空", trigger: "blur" }
    ],
    parentId: [
        { required: true, message: "上级机构不能为空", trigger: "blur" }
    ],
    orgName: [
        { required: true, message: "机构名称不能为空", trigger: "blur" }
    ],
    orgCode: [
        { required: true, message: "机构code不能为空", trigger: "blur" }
    ]
})
watch(() => form.orgCode, (newValue, _oldValue) => {
    // @ts-ignore
    form.orgCode = newValue.replace(/[\u4e00-\u9fa5/\s+/]|[^a-zA-Z0-9\u4E00-\u9FA5]/g, "")
}, {
    deep: true
})

/** 查询机构列表 */
function getList() {
    loading.value = true;
    listSysOrg(queryParams).then(response => {
        SysOrgList = proxy.$handleTree(response.data, "orgId")
        loading.value = false
        loading.value = false;
    });
}

getList();

/** 转换菜单数据结构 */
function normalizer(node: any) {
    if (node.children && !node.children.length) {
        delete node.children
    }
    return {
        id: node.orgId,
        label: node.orgName,
        children: node.children
    }
}
/** 查询机构下拉树结构 */
function getTreeSelect() {
    listSysOrg(queryParams).then(response => {
        orgOptions = []
        const org = { orgId: 0, orgName: '主类目', children: [] }
        org.children = proxy.$handleTree(response.data, "orgId")
        orgOptions.push(org)
    })
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 角色状态修改
function handleStatusChange(row) {
    let text = row.status === "0" ? "启用" : "停用";
    ElMessageBox.confirm('确认要"' + text + '""' + row.orgName + '"机构吗？').then(function () {
        return changeOrgStatus(row.orgId, row.status);
    }).then(() => {
        ElMessage.success(text + "成功");
    }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
    });
}

// 表单重置
function reset() {
    form = {
        orgId: "",
        orgName: undefined,
        orgCode: undefined,
        email: undefined,
        address: undefined,
        phone: undefined,
        linkMan: undefined,
        applyStatus: "0",
        parentId: "",
        parentIds: undefined,
        region: undefined,
        regionCode: undefined,
        orgImg: undefined,
        socialCode: undefined,
        province: undefined,
        city: undefined,
        county: undefined,
        deliverMark: "0",
        superviseMark: "0",
        cureMark: "0",
        archivesMark: "0",
        orgClass: "0",
        orgLevel: "1",
        orderNum: undefined,
        remark: "",
        status: '0'
    }
}

/** 新增按钮操作 */
function handleAdd(row) {
    reset();
    open.value = true;
    isEdit.value = false
    getTreeSelect()
    if (row != null && row.orgId) {
        form.parentId = row.orgId
    } else {
        form.parentId = "0"
    }
    title.value = "添加机构";
}
/** 修改按钮操作 */
function handleUpdate(row) {
    loading.value = true;
    isEdit.value = true
    reset();
    getTreeSelect()
    const orgId = row.orgId || ids
    getSysOrg(orgId).then(response => {
        loading.value = false;
        form = response.data;
        open.value = true;
        title.value = "修改机构";
    });
}

/** 提交按钮 */
function submitForm() {
    (formRef.value as any).validate(valid => {
        if (valid) {
            buttonLoading.value = true;
            if (form.orgId != null) {
                updateSysOrg(form).then(_response => {
                    ElMessage.success("修改成功");
                    open.value = false;
                    getList();
                }).finally(() => {
                    buttonLoading.value = false;
                });
            } else {
                addSysOrg(form).then(_response => {
                    ElMessage.success("新增成功");
                    open.value = false;
                    getList();
                }).finally(() => {
                    buttonLoading.value = false;
                });
            }
        }
    });
}
/** 删除按钮操作 */
function handleDelete(row) {
    const orgIds = row.orgId || ids;
    ElMessageBox.confirm('是否确认删除机构编号为"' + orgIds + '"的数据项？').then(() => {
        loading.value = true;
        return delSysOrg(orgIds);
    }).then(() => {
        loading.value = false;
        getList();
        ElMessage.success("删除成功");
    }).catch(() => {
    }).finally(() => {
        loading.value = false;
    });
}
/** 搜索按钮操作 */
function handleQuery() {
    queryParams.pageNum = 1;
    getList();
}
/** 重置按钮操作 */
function resetQuery() {
    // resetForm("queryForm");
    handleQuery();
}
/** 导出按钮操作 */
function handleExport() {
    // this.download('system/SysOrg/export', {
    //     ...this.queryParams
    // }, `SysOrg_${new Date().getTime()}.xlsx`)
}

</script>

<script lang = "ts">
export default {
    name: "SysOrg"
}
</script>

<style scoped>
.freePic ::v-deep .hide .el-upload--picture-card {
    display: none;
}
</style>
